/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 添加网页链接及小程序链接组件
 *  */

import React, { forwardRef, useState, useCallback, useEffect } from "react";
import { Form, Modal, Input, Row, Col, Button } from "antd";
import InputWithHttps from "../../components/InputWithHttps";

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const FormModal = Form.create()(({ title, visible, form, path, close, addLink = () => {} }) => {
  const { getFieldDecorator, validateFields, resetFields } = form;
  const [renderFom, setRenderForm] = useState([]);

  useEffect(
    () => {
      path == "web"
        ? setRenderForm([
            {
              field: "text",
              label: "文本内容",
              placeholder: "请输入文本内容",
              rules: [
                {
                  required: true,
                  message: "请输入文本内容",
                },
              ],
            },
            {
              field: "link",
              label: "链接地址",
              placeholder: "请输入链接地址",
              rules: [
                {
                  required: true,
                  message: "请输入链接地址",
                },
              ],
            },
          ])
        : setRenderForm([
            {
              field: "text",
              label: "文本内容",
              placeholder: "请输入文本内容",
              rules: [
                {
                  required: true,
                  message: "请输入文本内容",
                },
              ],
            },
            {
              field: "wx_id",
              label: "小程序ID",
              placeholder: "请输入小程序ID",
              rules: [
                {
                  required: true,
                  message: "请输入小程序ID",
                },
              ],
            },
            {
              field: "link",
              label: "跳转链接",
              placeholder: "请输入跳转链接",
              rules: [
                {
                  required: true,
                  message: "请输入跳转链接",
                },
              ],
            },
          ]);
    },
    [path]
  );

  const handleOk = useCallback(
    () => {
      validateFields((err, val) => {
        if (err) return;
        const { link, text, wx_id } = val;
        if (path === "web") {
          addLink(`<a href="${link}">${text}</a>`);
        } else {
          addLink(
            `<a href="https://m.kuaidihelp.com/" data-miniprogram-appid="${wx_id}" data-miniprogram-path="${link}">${text}</a>`
          );
        }
        handleCancel();
      });
    },
    [path, addLink, validateFields, handleCancel]
  );

  const handleCancel = useCallback(
    () => {
      close();
      resetFields();
    },
    [close, resetFields]
  );

  return (
    <Modal destroyOnClose visible={visible} title={title} onCancel={handleCancel} onOk={handleOk}>
      <Form {...formItemLayout}>
        {renderFom.map((val, index) => (
          <FormItem key={index} label={val.label}>
            {getFieldDecorator(val.field, {
              rules: val.rules,
            })(
              <InputWithHttps
                showAddBefore={path === "web" && val.field === "link"}
                placeholder={val.placeholder}
              />
            )}
          </FormItem>
        ))}
        <div>{path == "wxApp" && "注：跳转小程序需要和推送公众号关联才可推送"}</div>
      </Form>
    </Modal>
  );
});

const AddInfo = forwardRef((props, ref) => {
  const {
    value = '',
    onChange,
    form,
    onSubmit,
    onTest,
    onCancel,
    contentTitle = "推送文本内容",
    placeholder = "请输入内容",
  } = props;
  const { getFieldDecorator, validateFields, getFieldValue, setFieldsValue, resetFields } = form;
  const [visible, setVisible] = useState(false);
  const [title, setTitle] = useState("");
  const [type, setType] = useState("");

  const handleModal = useCallback(visible => {
    setVisible(visible);
  }, []);

  const handleOpenModal = useCallback(
    type => {
      handleModal(true);
      setType(type);
      type == "web" ? setTitle("插入超链接") : setTitle("插入小程序");
    },
    [handleModal]
  );

  const getFormValues = useCallback(
    (cb = () => {}) => {
      validateFields((err, val) => {
        cb(val.push_info, { err, resetFields });
      });
    },
    [validateFields, resetFields]
  );

  const handleOk = useCallback(
    () => {
      getFormValues((val, options) => {
        onSubmit && onSubmit(val, options);
        onChange && onChange(val, options);
      });
    },
    [onChange, onSubmit, getFormValues]
  );

  const handleTest = useCallback(
    () => {
      if (onTest) {
        getFormValues((val, options) => {
          onTest(val, options);
        });
      }
    },
    [onTest, getFormValues]
  );

  const handleCancel = useCallback(
    () => {
      onCancel && onCancel();
    },
    [onCancel]
  );

  const addLink = useCallback(
    link => {
      const oldVal = getFieldValue("push_info");
      setFieldsValue({
        push_info: `${oldVal}${link}`,
      });
    },
    [getFieldValue, setFieldsValue]
  );

  return (
    <div>
      <Row gutter={[0, 18]}>
        <Col>
          <Row type="flex" justify="space-between" style={{ fontSize: 16 }}>
            <Col>{contentTitle}</Col>
            <Col>
              <Row type="flex">
                <Col pull={4}>
                  <a onClick={() => handleOpenModal("web")}>插入网页链接</a>
                </Col>
                <Col>
                  <a onClick={() => handleOpenModal("wxApp")}>插入小程序</a>
                </Col>
              </Row>
            </Col>
          </Row>
        </Col>
        <Col>
          <Form>
            <FormItem>
              {getFieldDecorator("push_info", {
                initialValue: value,
                rules: [
                  {
                    required: true,
                    message: "请输入内容",
                  },
                ],
              })(<Input.TextArea rows="10" placeholder={placeholder} allowClear />)}
            </FormItem>
          </Form>
        </Col>
        <Col>
          <Row type="flex" justify="center" gutter={[30]}>
            {onCancel && (
              <Col>
                <Button onClick={handleCancel}>取消</Button>
              </Col>
            )}
            {onTest && (
              <Col>
                <Button onClick={handleTest}>测试</Button>
              </Col>
            )}
            <Col>
              <Button type="primary" onClick={handleOk}>
                确定
              </Button>
            </Col>
          </Row>
        </Col>
      </Row>
      <FormModal
        visible={visible}
        title={title}
        path={type}
        addLink={addLink}
        close={() => handleModal(false)}
      />
    </div>
  );
});

export default Form.create()(AddInfo);
